<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\aliyunoss\api\listen;

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Core\OssUtil;
use app\api\model\Config;

class UploadEnd
{
    public function handle($url)
    {
        $config = Config::getVal('app_aliyunoss');
        if (! empty($config['open']) && $config['open'] == 1) {
            $input           = input('post.');
            $accessKeyId     = $config["accessKeyId"];
            $accessKeySecret = $config["accessKeySecret"];
            $endpoint        = $config["endpoint"];
            $bucket          = $config["bucket"];
            $object          = str_replace('/upload/', $config["bucket"].'/upload/', $url);
            try{
                // 分片上传
                $objectFile = str_replace($config["bucket"].'/', public_path(), $object);
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->uploadFile($bucket, $object, $objectFile);
                // 删除本地文件
                @unlink($objectFile);
                return 'https://'.$bucket.'.'.$endpoint.'/'.$object;
            } catch(OssException $e) {
                throw new InvalidRootException($e->getMessage());
            }
        }
    }   
}